package com.gupao.javavip.rpc.framework.client;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ForeachLoadBalanceStrategy implements ILoadBalanceStrategy {
    private AtomicInteger lastIndex = new AtomicInteger(0);

    @Override
    public ServiceNode selectHost(List<String> serviceRepos) {
        if (serviceRepos == null || serviceRepos.isEmpty()) {
            throw new RuntimeException("服务列表为空");
        }

        if (serviceRepos.size() <= 1) {
            return build(serviceRepos.get(0));
        }

        if (lastIndex.get() <= 0) {
            lastIndex = new AtomicInteger(serviceRepos.size());
        }

        int index = lastIndex.getAndIncrement() % serviceRepos.size();
        return build(serviceRepos.get(index));
    }

    private ServiceNode build(String service) {
        ServiceNode node = new ServiceNode();

        String[] serviceInfo = service.split(":");
        node.setHost(serviceInfo[0]);
        node.setPort(Integer.valueOf(serviceInfo[1]));

        return node;
    }
}
